//
//  ImageTagsVC.m
//  MeiXiu
//
//  Created by Yuan on 13-2-1.
//
//

#import "MSTagsVC.h"
#import "DelTagView.h"
#import "UIColor+ColorUtils.h"
#import <QuartzCore/QuartzCore.h>

#define MAX_TAGS 10

@interface MSTagsVC ()<UITextFieldDelegate>
{
    IBOutlet UIScrollView *contentSC;
    IBOutlet UIScrollView *addtagSC;
    IBOutlet UIView *topView;
    IBOutlet UIView *bottomView;
    IBOutlet UILabel *selectTagLbl;
    IBOutlet UILabel *tagsCountLbl;
    IBOutlet UIButton *addTagBtn;
    IBOutlet UIPageControl *pControl;
    NSMutableArray *alltags;
    NSMutableArray *selectedArray;
}
@property(nonatomic,retain) UIScrollView *contentSC;
@property(nonatomic,retain) UIScrollView *addtagSC;
@property(nonatomic,retain) UIView *topView;
@property(nonatomic,retain) UIView *bottomView;
@property(nonatomic,retain) UILabel *selectTagLbl;
@property(nonatomic,retain) UILabel *tagsCountLbl;
@property(nonatomic,retain) UIButton *addTagBtn;
@property(nonatomic,retain) UIPageControl *pControl;
@property(nonatomic,retain) NSMutableArray *alltags;

@end

@implementation MSTagsVC
@synthesize contentSC;
@synthesize addTagBtn;
@synthesize addtagSC;
@synthesize topView;
@synthesize selectTagLbl;
@synthesize tagsCountLbl;
@synthesize pControl;
@synthesize alltags;
@synthesize bottomView;
@synthesize delegate;

-(void)dealloc
{
    [contentSC release];contentSC = nil;
    [addtagSC release];addtagSC = nil;
    [topView release];topView = nil;
    [bottomView release];bottomView = nil;
    [selectTagLbl release];selectTagLbl = nil;
    [tagsCountLbl release];tagsCountLbl = nil;
    [pControl release];pControl = nil;
    [alltags release];alltags = nil;
    [selectedArray release];selectedArray = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil tags:(NSString *)tags
{
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self)
    {
        NSArray *arr = [self allSaveTags];
        
        if (arr) {
            alltags = [[NSMutableArray alloc]initWithArray:arr];
        }
        else
        {            
            alltags = [[NSMutableArray alloc]initWithObjects:
                       HYLocalizedString(@"帅哥"),
                       HYLocalizedString(@"美女"),
                       HYLocalizedString(@"美发型男"),
                       HYLocalizedString(@"成熟闷骚型"),
                       HYLocalizedString(@"稳重"),
                       HYLocalizedString(@"小清新"),
                       HYLocalizedString(@"活泼可爱"),
                       HYLocalizedString(@"时尚一族"),
                       HYLocalizedString(@"踏实敬业"),
                       HYLocalizedString(@"观察力敏锐"),
                       HYLocalizedString(@"金剪子"),
                       HYLocalizedString(@"风流倜傥"),
                       HYLocalizedString(@"多愁善感"),
                       HYLocalizedString(@"造美专家"),
                       HYLocalizedString(@"艺术结合体"),
                       HYLocalizedString(@"与美发谈恋爱"),
                       HYLocalizedString(@"成熟时尚帅气"),
                       HYLocalizedString(@"奋斗ing"),
                       HYLocalizedString(@"好身材"),
                       HYLocalizedString(@"无法形容的帅"),
                       HYLocalizedString(@"艺术家"),
                       nil];
        }
        
        NSRange range = [tags rangeOfString:@" "];
        if (range.location == NSNotFound)
        {
            selectedArray = [[NSMutableArray alloc]init];
        }
        else
        {
            selectedArray = [[NSMutableArray alloc]initWithArray:[tags componentsSeparatedByString:@" "]];
        }
        
        HYLog(@"alltags--->%d",[alltags count]);
    }
    return self;
}

-(void)loadView
{
    [super loadView];
}


-(void)rightBarButtonItemAction:(UIButton *)btn
{
    NSString *result = @"";
   
    if ([selectedArray count]>0)
    {
       result =  [selectedArray componentsJoinedByString:@" "];
    }
    
    if (self.delegate&&[self.delegate respondsToSelector:@selector(ImageTagsVCFinsihed:)]) {
        [self.delegate ImageTagsVCFinsihed:result];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSArray *)allSaveTags
{
    NSUserDefaults *f = [NSUserDefaults standardUserDefaults];
    NSString *key = [NSString stringWithFormat:@"meishow.iosapp.userdefaulttags.%@",[[MSSetting sharedSetting]getAccountID]];
    return [f objectForKey:key];
}

-(void)saveTags:(NSArray *)arr
{
    NSString *key = [NSString stringWithFormat:@"meishow.iosapp.userdefaulttags.%@",[[MSSetting sharedSetting]getAccountID]];
    NSUserDefaults *f = [NSUserDefaults standardUserDefaults];
    [f setObject:arr forKey:key];
    [f synchronize];
}

-(void)allTagsView
{
    NSInteger pages = ceil((float)[alltags count]/12);
    self.pControl.numberOfPages = pages;
    self.pControl.currentPage = 0;
    [self.addtagSC setContentOffset:CGPointZero];
    self.addtagSC.pagingEnabled = YES;
    [self.addtagSC setShowsHorizontalScrollIndicator:NO];
    [self.addtagSC setContentSize:CGSizeMake(pages*282, 0)];
    NSInteger trows = 4;
    NSInteger tcols = 3;
    [self.addtagSC.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int page = 0 ; page < pages; page++)
    {
        for (int row = 0 ; row < trows; row++)
        {
            for (int col = 0 ; col < tcols ; col++)
            {
                
                NSInteger idx = page*12 + row*3 + col;
                if (idx>= [alltags count]) {
                    break;
                }
                CGFloat offset_x = page*282 + 10 + (84 + 10)*col;
                CGFloat offset_y = 10 + row*(36+10);
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                CGRect rect = CGRectMake(offset_x,offset_y,84,36);
                [btn setTitle:[alltags objectAtIndex:idx] forState:UIControlStateNormal];
                [btn setFrame:rect];
                btn.titleLabel.font = [UIFont systemFontOfSize:12.0f];
                [btn.titleLabel setTextAlignment:UITextAlignmentCenter];
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor colorWithRed:1.000 green:0.331 blue:0.604 alpha:1.000] forState:UIControlStateHighlighted];
                [btn setBackgroundColor:[UIColor whiteColor]];
                btn.layer.cornerRadius = 6.0f;
                btn.layer.masksToBounds = YES;
                btn.layer.borderWidth = 1.0f;
                btn.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.1].CGColor;
                btn.tag = idx;
                [btn addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
                [self.addtagSC addSubview:btn];
            }
        }
    }
}

-(void)selectTagsView
{
    [topView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    int rows = ceil((float)[selectedArray count]/2);
    int cols = 2;
    int totals = [selectedArray count];
    int tagVWidth = 130.0f;
    int tagVHeight = 38.0f;
    int space_x = 8.0f;
    int space_y = 5.0f;
    
    NSString *tagstip = [NSString stringWithFormat:@"(%d/10)",totals];
    [self.tagsCountLbl setText:tagstip];
    
    CGFloat tagview_offset_y = 0.0f;
    for (int row = 0 ; row < rows; row++)
    {
        for (int col = 0 ; col < cols ; col++)
        {
            int idx = row*cols + col;
            if (idx>=totals)break;
            tagview_offset_y = space_y + (space_y + tagVHeight)*row;
            CGRect rect = CGRectMake(space_x + (space_x + tagVWidth)*col, tagview_offset_y, tagVWidth, tagVHeight);
            DelTagView *v = [[DelTagView alloc]initWithFrame:rect withTitle:[selectedArray objectAtIndex:idx] delegage:self];
            v.btn.tag = idx;
            [topView addSubview:v];
            [v release];
            tagview_offset_y += (tagVHeight +space_y);
        }
    }
    
    CGRect topviewframe = self.topView.frame;
    topviewframe.size.height =  tagview_offset_y;
    
    CGRect bottomFrame = self.bottomView.frame;
    bottomFrame.origin.y = topviewframe.origin.y+topviewframe.size.height + 10.0f;
    
    [UIView animateWithDuration:0.3 animations:^(void){
        self.topView.frame  = topviewframe;
        self.bottomView.frame = bottomFrame;
    }];
    
    self.contentSC.contentSize = CGSizeMake(0,bottomFrame.size.height+bottomFrame.origin.y);
}

-(void)removeTag:(UIButton *)btn
{
    if (btn.tag < [selectedArray count]) {
        [selectedArray removeObjectAtIndex:btn.tag];
        [self selectTagsView];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
 
    [self allTagsView];
}


-(void)tagClick:(UIButton *)btn
{
    if ([selectedArray count]>= MAX_TAGS)
    {
        return [MSTool showAlert:HYLocalizedString(@"最多只能添加10个标签！")];
    }
    NSString *tag = [alltags objectAtIndex:btn.tag];
    if (![selectedArray containsObject:tag]) {
        [selectedArray addObject:tag];
        [self selectTagsView];
    }
}

- (void)viewDidLoad
{
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];

    [self setTitle:HYLocalizedString(@"描述标签") showBackButton:YES];
    
    [self selectTagsView];
    
    [self.addTagBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.addTagBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.addTagBtn setBackgroundColor:[UIColor whiteColor]];
    addTagBtn.layer.cornerRadius = 6.0f;
    addTagBtn.layer.masksToBounds = YES;
    addTagBtn.layer.borderWidth = 1.0f;
    addTagBtn.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.1].CGColor;
    
    self.addtagSC.delegate  = self;
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.03];
    self.topView.layer.masksToBounds = YES;
    self.topView.layer.cornerRadius = 8.0f;
    self.topView.layer.borderWidth = 1.0f;
    self.topView.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.1].CGColor;
    self.topView.backgroundColor = [UIColor whiteColor];
    
    UIImage *addImg = [UIImage imageNamed:@"mreg_08.png"];
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.userInteractionEnabled = YES;
    btn.showsTouchWhenHighlighted = YES;
    [btn setTitle:HYLocalizedString(@"完成") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(fAction:) forControlEvents:UIControlEventTouchDown];
    btn.frame = CGRectMake(0.0f, 0.0f,addImg.size.width/2,addImg.size.height/1.6);
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0f]];
    [btn setBackgroundImage:addImg forState:UIControlStateNormal];
    [btn setBackgroundImage:addImg forState:UIControlStateHighlighted];
    UIBarButtonItem *item=[[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem =item;
    [item release];

    self.view.backgroundColor = [UIColor colorWithString:@"#f1eee9"];

    [self performSelector:@selector(showView) withObject:nil afterDelay:0.5];
    
    [self setRightItem:HYLocalizedString(@"确定")];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)showView
{
    self.contentSC.hidden = NO;
}

-(IBAction)addTag:(id)sender
{
    UIAlertView *cAlertView  = [[UIAlertView alloc]
                                initWithTitle:HYLocalizedString(@"添加新标签")
                                message:@"\n"
                                delegate:self
                                cancelButtonTitle:nil
                                otherButtonTitles:HYLocalizedString(@"确定"), HYLocalizedString(@"取消"), nil];
    
    UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(12,45, 260, 29)];
    txtField.borderStyle = UITextBorderStyleRoundedRect;
    txtField.placeholder = HYLocalizedString(@"添加的标签不超过六个字符");
    txtField.tag = 101;
    txtField.delegate = self;
    txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    cAlertView.tag = 100;
    [cAlertView addSubview:txtField];
    [cAlertView show];
    //show alert 和 becomefirstresponder不能同时进行，会影响ui交互和收到警告
    [txtField performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.5];
    [txtField release];
    [cAlertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{        
    if (alertView.tag == 100)
    {
        if (buttonIndex != 0)
        {
            return;
        }
        UITextField *txtField = (UITextField*)[alertView viewWithTag:101];
        if (txtField != nil)
        {
            if (txtField.text == nil || [txtField.text length]<1)
            {
                [self addTag:nil];
            }
            else
            {
                if (![alltags containsObject:txtField.text])
                {
                    NSArray *arr = [NSArray arrayWithArray:alltags];
                    [alltags removeAllObjects];
                    [alltags addObject:txtField.text];
                    [alltags addObjectsFromArray:arr];
                    [self saveTags:alltags];
                    [self allTagsView];
                }
                if (![selectedArray containsObject:txtField.text])
                {
                    if ([selectedArray count]>=MAX_TAGS)
                    {
                        [MSTool showAlert:HYLocalizedString(@"最多只能添加10个标签！")];
                    }
                    else
                    {
                        [selectedArray addObject:txtField.text];
                        [self selectTagsView];
                    }
                }
                else
                {
                    [MSTool showAlert:HYLocalizedString(@"已经添加该标签了")];
                }
            }
        }
    }
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 101)
    {
        if (string.length!=0)
        {
            if (textField.text.length+string.length>6)
            {
                return NO;
            }
            return YES;
        }else
            return YES;
    }else
        return YES;
}



- (void)scrollViewDidScroll:(UIScrollView *)_selfScV
{
    CGFloat pageWidth = _selfScV.frame.size.width;
    int page = floor((_selfScV.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    HYLog(@"begindrag");
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    HYLog(@"enddecelerating");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
